//
//  PICheck.m
//  playin
//
//  Created by playin on 2019/5/8.
//  Copyright © 2019 A. All rights reserved.
//

#import "PICheck.h"
#import "PIHttpManager.h"
#import "PIUtil.h"
#import "PIDeviceInfo.h"
#import "PICommon.h"

@implementation PICheck


+ (void)checkAvaliableWithDeviceID:(NSString *)deviceID
                          callback:(void(^)(BOOL result))avaliable {
    
    if (![PIUtil validStr:deviceID]) {
        NSLog(@"[PICheck] check avaliable error: deviceID is invalid");
        [self handleResult:NO callback:avaliable];
        return;
    }
    NSString *urlStr = [NSString stringWithFormat:@"http://3.112.73.171/adtiming/device/chcek"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:deviceID forKey:@"device_id"];
    [PIHttpManager post:urlStr params:params success:^(NSDictionary * _Nonnull result) {
        NSLog(@"[PICheck] check avaliable result: %@", result);
        dispatch_async(dispatch_get_main_queue(), ^{
            id connected = [result valueForKey:@"connected"];
            if (![PIUtil validObj:connected]) {
                [self handleResult:NO callback:avaliable];
                return;
            }
            int code_value = [connected intValue];
            if (code_value == 0) {
                [self handleResult:NO callback:avaliable];
            } else {
                [self handleResult:YES callback:avaliable];
            }
        });
    } failure:^(NSDictionary * _Nonnull error) {
        NSLog(@"[PICheck] check avaliable error: %@", error);
        [self handleResult:NO callback:avaliable];
    }];
}

+ (void)handleResult:(BOOL)result callback:(void(^)(BOOL result))avaliable {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (avaliable) {
            avaliable(result);
        }
    });
}

@end
